package net.vinote.smart.platform.service.dw;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import javax.servlet.http.HttpServletRequest;

import net.vinote.smart.platform.comm.StringFunction;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.module.log.RunLogger;
import net.vinote.smart.platform.service.SRE;
import net.vinote.smart.platform.service.dw.html.HtmlTag;
import net.vinote.smart.platform.service.util.ShowStyle;

/**
 * 数据窗体的详情页面,也功能包括页面的生成及数据的装载
 */
public class DataWindowInfo extends DataWindow {

	public DataWindowInfo(HttpServletRequest request) {
		super(request);
		setShowStyle(ShowStyle.INFO);
	}

	@Override
	protected String getDWHtml() throws SQLException {
		if (getDwCatalog() == null) {
			RunLogger.getLogger().log(Level.WARNING,
					"显示模板:" + getDoNo() + "未定义!");
			return "<span>显示模板:" + getDoNo() + "未定义!</span>";
		}

		// 读取数据
		List<BizObject> dataList = getDataList();
		BizObject dataBo = null;
		if (dataList != null && dataList.size() == 1) {
			dataBo = dataList.get(0);
		} else {
			dataBo = new BizObject();
		}
		Map<String, HtmlTag> tagMap = getHtmlTagMap(dataBo);
		int maxColumnNum = getColumnNum();// 当前显示模板支持的单行最多列数
		int index = 0;
		Map<Integer, Integer> matrixMap = new HashMap<Integer, Integer>();
		int curRow = 0;
		StringBuffer sb = new StringBuffer(
				"<table cellpadding='0' cellspacing='0' border='0' width='100%' class='dwInfo'>");
		boolean needPairTdFlag = false;
		boolean pairTrFlag = true;// tr标签是否以配对
		for (String key : tagMap.keySet()) {
			HtmlTag tag = tagMap.get(key);

			if (tag.getColSpan() > 0 && needPairTdFlag) {
				sb.append("</td>");
				needPairTdFlag = false;
			}

			if ((index % maxColumnNum == 0 || index == 0) && !needPairTdFlag) {
				if (!pairTrFlag) {
					sb.append("</tr>");
				}
				sb.append("<tr>");
				pairTrFlag = false;
				Integer v = matrixMap.get(++curRow);
				if (v != null) {
					index += v;
				}
			}
			if ("O".equalsIgnoreCase(tag.getDataObj())) {
				tag.setValue(StringFunction.nullToBlank(dataBo.getAttribute(tag
						.getColField())));
			} else if (StringFunction.nullToBlank(tag.getDataObj()).length() > 0) {
				tag.setValue(StringFunction.nullToBlank(dataBo.getAttribute(tag
						.getDataObj() + "." + tag.getColField())));
			}
			if (!tag.isVisible()) {
				sb.append(tag.getHtml());
				continue;
			}

			// 若由于跨列导致换行,则对上一行进行补缺口
			if (tag.getColSpan() > 1
					&& index % maxColumnNum + tag.getColSpan() > maxColumnNum) {
				sb.append("<td>&nbsp;</td><td colspan='"
						+ (index % maxColumnNum + tag.getColSpan() - maxColumnNum)
						+ "'>&nbsp;</td></tr><tr>");
				pairTrFlag = true;
				index = maxColumnNum;
				Integer v = matrixMap.get(++curRow);
				if (v != null) {
					index += v;
				}
			}

			// colspan>0的标签确保之前的td标签已配对
			if (tag.getColSpan() > 0 || index == 0) {
				sb.append(
						"<td"
								+ (tag.getRowSpan() > 1 ? " rowspan='"
										+ tag.getRowSpan() + "'" : "")
								+ "><pre>").append(tag.getTagName());
				if (tag.isRequired()) {
					sb.append("&nbsp;<span style='color:red'>*<span class='missingMessage'></span></span>");
				}
				sb.append("</pre></td>");

				sb.append("<td ");
				if (tag.getColSpan() > 1) {
					sb.append("colspan='").append(2 * tag.getColSpan() - 1)
							.append("' ");
				}
				if (tag.getAlign() != null) {
					sb.append("align='").append(tag.getAlign()).append("' ");
				}
				if (tag.getRowSpan() > 1) {
					sb.append("rowspan='").append(tag.getRowSpan())
							.append("' ");
					int rows = tag.getRowSpan();
					while (--rows > 0) {
						Integer v = matrixMap.get(curRow + rows);
						matrixMap.put(curRow + rows, v == null ? 1 : v + 1);
					}
				}
				if (tag.isRequired()) {
					StringBuffer options = new StringBuffer(
							StringFunction.nullToBlank(tag
									.getAttribute("data-options")));
					if (options.length() > 0) {
						options.append(",");
					}
					options.append("required:true");
					tag.setAttribute("data-options", options.toString());
				}
				tag.setValue(StringFunction.nullToBlank(tag.getValue())
						.replace("'", "&apos;"));
				sb.append(">").append(tag.getHtml());

				sb.append("&nbsp;").append(tag.getAfterField());

				needPairTdFlag = true;
			} else {
				sb.append(tag.getHtml());
				if (!StringFunction.isBlank(tag.getAfterField())) {
					sb.append("&nbsp;").append(tag.getAfterField());
				}
			}
			// if (tag.getColSpan() > 0) {
			// sb.append("</td>");
			// }
			// 不添加最后一个</tr>标签
			// if (index % maxColumnNum == maxColumnNum - 1
			// && index < tagMap.size()) {
			// sb.append("</tr>");
			// }
			index += tag.getColSpan();
		}
		sb.append("</td>");
		// 剩余部分补空列
		while (index++ % maxColumnNum != 0) {
			sb.append("<td>&nbsp;</td><td>&nbsp;</td>");
		}
		sb.append("</tr>");
		sb.append("</table>");
		sb.append("<input type='hidden' name='O.isinsert' value='")
				.append(isInsert()).append("'/>");
		return sb.toString();
	}

	/**
	 * 该显示模板单行显示的字段数
	 **/
	private int getColumnNum() {
		int item = getDwCatalog().getItemNum();
		int maxItem = SRE.getSystemParameter().getDwInfoMaxItems();
		// 注:先比较maxItem,防止该参数配置有误导致页面无法展示
		if (item > maxItem) {
			item = maxItem;
		}
		if (item < 1) {
			item = 1;
		}
		return item;
	}
}
